//! 中断管理模块
//! 
//! 提供中断处理和管理功能

use crate::utils::error::{YayaError, Result};

/// 中断类型
#[derive(Debug, Clone, PartialEq)]
pub enum InterruptType {
    Timer,      // 定时器中断
    Keyboard,   // 键盘中断
    Mouse,      // 鼠标中断
    Network,    // 网络中断
    Storage,    // 存储设备中断
    Generic,    // 通用中断
}

/// 中断处理函数类型
pub type InterruptHandler = fn(interrupt_number: u8) -> Result<(), YayaError>;

/// 中断描述符
pub struct InterruptDescriptor {
    pub interrupt_number: u8,
    pub interrupt_type: InterruptType,
    pub handler: InterruptHandler,
    pub enabled: bool,
}

/// 中断管理器
pub struct InterruptManager {
    descriptors: Vec<InterruptDescriptor>,
    idt_configured: bool,
}

impl InterruptManager {
    /// 创建新的中断管理器
    pub fn new() -> Result<Self, YayaError> {
        Ok(InterruptManager {
            descriptors: Vec::new(),
            idt_configured: false,
        })
    }
    
    /// 初始化中断子系统
    pub fn init() -> Result<(), YayaError> {
        info!("初始化中断子系统");
        
        // 配置中断描述符表（IDT）
        // 初始化可编程中断控制器（PIC）
        
        Ok(())
    }
    
    /// 关闭中断子系统
    pub fn shutdown() -> Result<(), YayaError> {
        info!("关闭中断子系统");
        Ok(())
    }
    
    /// 注册中断处理程序
    pub fn register_handler(&mut self, interrupt_number: u8, handler: InterruptHandler, interrupt_type: InterruptType) -> Result<(), YayaError> {
        let descriptor = InterruptDescriptor {
            interrupt_number,
            interrupt_type,
            handler,
            enabled: true,
        };
        
        self.descriptors.push(descriptor);
        info!("注册中断处理程序: 中断号 {}", interrupt_number);
        
        Ok(())
    }
    
    /// 启用中断
    pub fn enable_interrupt(&mut self, interrupt_number: u8) -> Result<(), YayaError> {
        if let Some(desc) = self.descriptors.iter_mut().find(|d| d.interrupt_number == interrupt_number) {
            desc.enabled = true;
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("未找到指定中断".into()))
        }
    }
    
    /// 禁用中断
    pub fn disable_interrupt(&mut self, interrupt_number: u8) -> Result<(), YayaError> {
        if let Some(desc) = self.descriptors.iter_mut().find(|d| d.interrupt_number == interrupt_number) {
            desc.enabled = false;
            Ok(())
        } else {
            Err(YayaError::InvalidParameter("未找到指定中断".into()))
        }
    }
    
    /// 处理中断
    pub fn handle_interrupt(&self, interrupt_number: u8) -> Result<(), YayaError> {
        if let Some(desc) = self.descriptors.iter().find(|d| d.interrupt_number == interrupt_number && d.enabled) {
            (desc.handler)(interrupt_number)
        } else {
            warn!("未处理的中断: {}", interrupt_number);
            Ok(())
        }
    }
}

/// 获取全局中断管理器实例
pub fn get_interrupt_manager() -> &'static mut InterruptManager {
    static mut INTERRUPT_MANAGER: Option<InterruptManager> = None;
    
    unsafe {
        if INTERRUPT_MANAGER.is_none() {
            INTERRUPT_MANAGER = Some(InterruptManager::new().unwrap());
        }
        INTERRUPT_MANAGER.as_mut().unwrap()
    }
}